import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { firstMenu } from '@/utils/mapMenus'
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import(/* webpackChunkName: "main" */ '../views/main/main.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    component: () => import(/* webpackChunkName: "notFound" */ '../views/notfound/index.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to) => {
  if (to.name !== 'login') {
    const JsonToken = localStorage.getItem('token')
    if (!JsonToken) {
      return { name: 'login' }
    }
  }
  // 重定向到菜单的第一项
  if (to.name === 'main') {
    return firstMenu.path
  }
})

export default router
